package com.bbcare.followup.plat.service.impl;

import java.util.*;

import com.bbcare.comm.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.bbcare.comm.DateTimeUtil;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IGy3yService;
import com.bbcare.followup.plat.task.TaskComparator;


@Service
public class Gy3yService implements IGy3yService {
    private final static Logger logger = Logger.getLogger(Gy3yService.class);

    @Autowired
    private IPatientService patientService;

    @Autowired
    private JdbcTemplate jdbc;


    /**
     * 计算体格周增长。
     * @param followupDate 本次随访日期
     * @param selectedTaskId 本次随访taskId
     * @param tgMap 本次随访的体格数据，tz体重sc身长tw头围。
     * @return
     * @throws Exception
     */
    @Override
    public Map<String,String> dealGrowthWeekly(final String followupDate, final String selectedTaskId, final Map<String,String> tgMap) throws Exception {
        String taskId, taskName, finishDate, tz="",sc="",tw="",retTz="",retSc="",retTw="";
        Map<String,String> retMap   = new HashMap<>();

        String querySql   = "SELECT user_id, pt_schemeid, queue_id FROM pt_task_info WHERE id='"+selectedTaskId+"'";
        List<Map<String,Object>> rowlist    = jdbc.queryForList(querySql);
        final String patientId  = rowlist.get(0).get("user_id").toString();
        final String schemeId   = rowlist.get(0).get("pt_schemeid").toString();
        //final String queueId    = rowlist.get(0).get("queue_id").toString();
        Map<String,Object> paraMap = new HashMap<>();
        paraMap.put("ptSchemeId",   schemeId);
        paraMap.put("taskFlag",     "1");
        List<Object> taskList  = patientService.qryPatientTaskList(paraMap);
        final int size  = taskList.size();
        if (size<2) {
            retMap.put("retMsg",    "没有找到前次计划随访或临时随访！！");
            return retMap;
        }

        Collections.sort(taskList, new TaskComparator());    //重新排序这些随访任务。
        Map<String,Object> taskRefMap   = null;
        int i,j,selectIdx=size-1;
        for(i=1; i!=size; i++)  {
            taskRefMap = (Map)taskList.get(i);
            if (!taskRefMap.get("taskId").equals(selectedTaskId))    {
                continue;
            } else {
                //当前选中的随访任务索引i。
                selectIdx   = i;
                break;
            }
        }

        double distance=0.0d, dTz=0.0d, dSc=0.0d,dTw=0.0d;
        String strDistance    = "";
        for(j=selectIdx-1; j!=0; j--)   {
            taskRefMap  = (Map)taskList.get(j);
            taskId      = taskRefMap.get("taskId").toString();
            taskName    = taskRefMap.get("taskName").toString();
            finishDate  = taskRefMap.get("finishDate").toString();  //前次随访日期。
            if (StringUtils.isNotBlank(finishDate)) {
                //这是前序已完成的随访任务，查询问卷中的体重。
                querySql = "SELECT question_answer FROM pt_contentdata_info WHERE question_id='zcey_tz' AND task_id='" + taskId + "' AND user_id='" + patientId + "' AND pt_schemeid='" + schemeId + "'";
                rowlist = jdbc.queryForList(querySql);
                if (0 != rowlist.size()) {
                    tz = rowlist.get(0).get("question_answer").toString();
                }
                if (StringUtils.isBlank(tz))    {
                    querySql = "SELECT question_answer FROM pt_contentdata_info WHERE question_id='zcru_tz' AND task_id='" + taskId + "' AND user_id='" + patientId + "' AND pt_schemeid='" + schemeId + "'";
                    rowlist = jdbc.queryForList(querySql);
                    if (0 != rowlist.size()) {
                        tz = rowlist.get(0).get("question_answer").toString();
                    }
                }

                querySql = "SELECT question_answer FROM pt_contentdata_info WHERE question_id='zcey_sc' AND task_id='" + taskId + "' AND user_id='" + patientId + "' AND pt_schemeid='" + schemeId + "'";
                rowlist = jdbc.queryForList(querySql);
                if (0 != rowlist.size()) {
                    sc = rowlist.get(0).get("question_answer").toString();
                }
                if (StringUtils.isBlank(sc))    {
                    querySql = "SELECT question_answer FROM pt_contentdata_info WHERE question_id='zcru_sc' AND task_id='" + taskId + "' AND user_id='" + patientId + "' AND pt_schemeid='" + schemeId + "'";
                    rowlist = jdbc.queryForList(querySql);
                    if (0 != rowlist.size()) {
                        sc = rowlist.get(0).get("question_answer").toString();
                    }
                }

                querySql = "SELECT question_answer FROM pt_contentdata_info WHERE question_id='zcey_tw' AND task_id='" + taskId + "' AND user_id='" + patientId + "' AND pt_schemeid='" + schemeId + "'";
                rowlist = jdbc.queryForList(querySql);
                if (0 != rowlist.size()) {
                    tw = rowlist.get(0).get("question_answer").toString();
                }
                if (StringUtils.isBlank(tw))    {
                    querySql = "SELECT question_answer FROM pt_contentdata_info WHERE question_id='zcru_tw' AND task_id='" + taskId + "' AND user_id='" + patientId + "' AND pt_schemeid='" + schemeId + "'";
                    rowlist = jdbc.queryForList(querySql);
                    if (0 != rowlist.size()) {
                        tw = rowlist.get(0).get("question_answer").toString();
                    }
                }

                if (StringUtils.isBlank(tz) && StringUtils.isBlank(sc) && StringUtils.isBlank(tw))    {
                    //这次随访的体格全部未填写。
                    continue;
                }

                //计算周增长。
                try {
                    //2次随访的日期间隔。
                    distance = DateUtil.daysBetweenDateStr(finishDate, followupDate);
                    if (tgMap.containsKey("tz")) {
                        dTz = Double.valueOf(tz).doubleValue() * 1000;    //上次随访时的体重，kg换算成g。
                        final double dBctz  = Double.valueOf(tgMap.get("tz")).doubleValue();    //本次随访时的体重g。
                        final double tzGrow = dBctz - dTz;  //体重的增长。
                        final double growWeekly = tzGrow / distance * 7;
                        final int iGrowWeekly   = (int)growWeekly;
                        retTz   = Integer.valueOf(iGrowWeekly).toString();
                        logger.info("体重周增长："+retTz+"(g)");
                    }
                    if (tgMap.containsKey("sc")) {
                        dSc = Double.valueOf(sc).doubleValue();
                        final double dBcsc  = Double.valueOf(tgMap.get("sc")).doubleValue();
                        final double scGrow = dBcsc - dSc;
                        final double growWeekly = scGrow / distance * 7;
                        //retSc   = Double.valueOf(growWeekly).toString();
                        retSc   = String.format("%.1f", growWeekly);
                        logger.info("身长周增长："+retSc+"(cm)");
                    }
                    if (tgMap.containsKey("tw")) {
                        dTw = Double.valueOf(tw).doubleValue();
                        final double dBctw  = Double.valueOf(tgMap.get("tw")).doubleValue();
                        final double twGrow = dBctw - dTw;
                        final double growWeekly = twGrow / distance * 7;
                        //retTw   = Double.valueOf(growWeekly).toString();
                        retTw   = String.format("%.1f", growWeekly);
                        logger.info("头围周增长："+retTw+"(cm)");
                    }
                } catch (Exception ex)  {
                    logger.error(ex);
                }

                if (StringUtils.isNotBlank(retTz) || StringUtils.isNotBlank(retSc) || StringUtils.isNotBlank(retTw)) {
                    //可以正常计算出体格3项中的1项，就返回这1项数据。
                    retMap.put("本次随访日期",    followupDate);
                    retMap.put("本次随访taskId",  selectedTaskId);
                    if (tgMap.containsKey("tz") && StringUtils.isNotBlank(tgMap.get("tz"))) {
                        retMap.put("本次随访体重(g)",  tgMap.get("tz"));
                    }
                    if (tgMap.containsKey("sc") && StringUtils.isNotBlank(tgMap.get("sc"))) {
                        retMap.put("本次随访身长(cm)",  tgMap.get("sc"));
                    }
                    if (tgMap.containsKey("tw") && StringUtils.isNotBlank(tgMap.get("tw"))) {
                        retMap.put("本次随访头围(cm)",  tgMap.get("tw"));
                    }

                    retMap.put("前次随访名称",    taskName);
                    retMap.put("前次随访日期",    finishDate);
                    if (StringUtils.isNotBlank(tz)) {
                        retMap.put("前次随访体重(g)", Double.valueOf(dTz).toString());
                    }
                    if (StringUtils.isNotBlank(sc)) {
                        retMap.put("前次随访身长(cm)",sc);
                    }if (StringUtils.isNotBlank(tw)) {
                        retMap.put("前次随访头围(cm)", tw);
                    }
                    strDistance    = Integer.valueOf((int)distance).toString();
                    retMap.put("二次随访间隔（天）",    strDistance);

                    retMap.put("tz_zzz",  retTz);  //体重周增长。
                    retMap.put("sc_zzz",  retSc);  //身长周增长。
                    retMap.put("tw_zzz",  retTw);  //头围周增长。
                    retMap.put("体重周增长(g)", retTz);  //体重周增长。
                    retMap.put("身长周增长(cm)", retSc);  //身长周增长。
                    retMap.put("头围周增长(cm)", retTw);  //头围周增长。
                    break;
                } else {
                    //继续找前1次随访，可能是这次随访的体格数据全部没有填写。
                }
            }
        }

        return retMap;
    }

    /**
     * 根据母亲手机号查询父母、家庭基本信息。
     * @param motherPhone
     * @param queueId 基本队列ID（高危儿队列）
        母亲姓名zcejd_mqxm
        父亲姓名zcejd_fqxm
        父亲手机号zcejd_fqsjhm
        常住地址zcejd_jtzz
     */
    @Override
    public Map<String,Object> queryParentInfo(String motherPhone, String queueId)  {
        final String[] questionIds  = {"Pub1100001","zcejd_mqxm","zcejd_fqxm","zcejd_fqsjhm","zcejd_jtzz","zcejd_mqnl","zcejd_mqmz","zcejd_mqsfzh","zcejd_mqjycd","zcejd_mqcsd","zcejd_fqnl","zcejd_hkdz"};
        Map<String,Object> retMap   = new HashMap<>();
        String sql  = "SELECT id FROM pt_user_info WHERE phone_no='" + motherPhone + "' AND tenant_id!='0' AND id IN (SELECT user_id FROM pt_queuescheme_info WHERE queue_id='" +queueId + "' AND user_status='1') ORDER BY birthday ASC";
        List<Map<String,Object>> rowlist    = jdbc.queryForList(sql);
        if (null != rowlist && !rowlist.isEmpty())  {
            String babyId   = rowlist.get(0).get("id").toString();
            for(String questionId : questionIds) {
                sql = "SELECT question_answer FROM pt_contentdata_info WHERE question_id='" + questionId + "' AND question_answer!='' AND user_id='" + babyId + "' " + "AND queue_id='" + queueId + "'";
                logger.info("queryParentInfo() sql:" + sql);
                List<Map<String, Object>> answerList = jdbc.queryForList(sql);
                if (null != answerList && !answerList.isEmpty()) {
                    retMap.put(questionId, answerList.get(0).get("question_answer"));
                }
            }
        }

        return retMap;
    }
}
